/* 下一个排列 */

#include<iostream>
#include<algorithm>
using namespace std;

void NextPermutation(int *pStart, int *pEnd)
{
	int* p = pEnd - 1;
	int* q = p--;

	for (; p != pStart; p--, q--)
	{
		if (*p < *q)
		{
			break;
		}
	}

	if (p == pStart)
	{
		int *q = pEnd - 1;

		while (p < q)
		{
			int temp = *p;
			*p = *q;
			*q = temp;

			p--;
			q++;
		}
	}
	else
	{
		int *q = pEnd - 1;

		while (*q < *p)
		{
			q--;
		}

		int temp = *p;
		*p = *q;
		*q = temp;

		p++;
		q = pEnd - 1;
		while (p < q)
		{
			int temp = *p;
			*p = *q;
			*q = temp;

			p++;
			q--;
		}
	}
}

int main(void)
{
	int a[] = { 1, 2, 3, 4, 5, 6 };

	for (int i = 0; i < 100; i++)
	{
		NextPermutation(a, a + 6);
		for_each(a, a + 6, [](int e) -> void {cout << e << ", "; });
		cout << "\n";
	}

	return 0;
}
